package com.chat.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chat.admin.service.GroupService;
import com.chat.admin.service.IDisableGroupService;
import com.chat.common.common.exception.RoutineException;
import com.chat.common.dto.DisableGroupDTO;
import com.chat.common.dto.GetGroupDTO;
import com.chat.common.entity.DisableGroup;
import com.chat.common.form.ListForm;
import com.chat.common.vo.GetGroupVO;
import com.chat.common.vo.R;
import com.chat.openfeign.client.BusinessDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    BusinessDataService businessDataService;

    @Autowired
    IDisableGroupService idisableGroupService;

    @Override
    public R<ListForm<GetGroupVO>> getGroupList(GetGroupDTO getGroupDTO) {
        return businessDataService.getAllGroups(getGroupDTO);
    }

    @Override
    @Transactional
    public R DisableGroup(DisableGroupDTO disableGroupDTO) {
        //调用群聊模块
        R result = businessDataService.DisableGroup(disableGroupDTO.getGroupId());
        if (result != null && result.getCode() == 200){
            DisableGroup disabledGroup = new DisableGroup();
            BeanUtil.copyProperties(disableGroupDTO, disabledGroup);
            disabledGroup.setCreationTime(LocalDateTime.now());
            //保证原因只有一个。所以先删除以前的
            QueryWrapper<DisableGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id",disableGroupDTO.getGroupId());
            idisableGroupService.getBaseMapper().delete(queryWrapper);
            int insert = idisableGroupService.getBaseMapper().insert(disabledGroup);
            if (insert == 0) {
                throw new RoutineException("禁用群聊失败");
            }
            return R.succeed("群聊已成功禁用");
        } else {
            throw new RoutineException("禁用群聊失败");
        }

    }

    @Override
    public R EnableGroup(Long id) {
        return businessDataService.EnableGroup(String.valueOf(id));
    }
}
